// 当页面加载完成时执行
document.addEventListener("DOMContentLoaded", function () {
    // 1. 轮播图功能
    let currentSlide = 0;
    const slides = document.querySelectorAll(".carousel-item");
    const dots = document.querySelectorAll(".carousel-btn");
    const carouselInner = document.getElementById("carouselInner");

    function showSlide(index) {
        carouselInner.style.transform = `translateX(-${index * 100}%)`;

        // 更新指示点状态
        dots.forEach((dot, i) => {
            dot.classList.toggle("active", i === index);
        });

        currentSlide = index;
    }

    // 自动轮播
    setInterval(() => {
        let nextSlide = (currentSlide + 1) % slides.length;
        showSlide(nextSlide);
    }, 5000);

    // 点击指示点切换
    dots.forEach((dot, index) => {
        dot.addEventListener("click", () => {
            showSlide(index);
        });
    });

    // 2. 侧边栏功能
    const sidebar = document.getElementById("sidebar");
    const sidebarToggle = document.getElementById("sidebarToggle");
    const closeSidebar = document.getElementById("closeSidebar");

    sidebarToggle.addEventListener("click", () => {
        sidebar.classList.add("active");
    });

    closeSidebar.addEventListener("click", () => {
        sidebar.classList.remove("active");
    });

    // 3. 选项卡功能
    const tabBtns = document.querySelectorAll(".tab-btn");
    const tabPanes = document.querySelectorAll(".tab-pane");

    tabBtns.forEach((btn) => {
        btn.addEventListener("click", () => {
            // 移除所有活动状态
            tabBtns.forEach((b) => b.classList.remove("active"));
            tabPanes.forEach((pane) => pane.classList.remove("active"));

            // 添加当前活动状态
            btn.classList.add("active");
            const tabId = btn.getAttribute("data-tab");
            document.getElementById(`${tabId}Tab`).classList.add("active");

            // 如果是地图选项卡，初始化地图
            if (tabId === "map") {
                initMap();
            }
        });
    });

    // 4. 初始化地图
    function initMap() {
        if (document.getElementById("map").hasChildNodes()) return;

        const map = L.map("map").setView([39.9042, 116.4074], 13);

        L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
            attribution:
                '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        }).addTo(map);

        // 添加标记
        L.marker([39.9042, 116.4074])
            .addTo(map)
            .bindPopup("北京市中心")
            .openPopup();
    }

    // 5. 天气API调用
    const getWeatherBtn = document.getElementById("getWeather");
    const cityInput = document.getElementById("cityInput");
    const cityError = document.getElementById("cityError");
    const weatherResult = document.getElementById("weatherResult");

    getWeatherBtn.addEventListener("click", () => {
        const city = cityInput.value.trim();

        // 表单验证
        if (!city) {
            cityError.style.display = "block";
            return;
        }

        cityError.style.display = "none";

        // 模拟API调用
        document.getElementById("cityName").textContent = city;
        document.getElementById("temperature").textContent = Math.floor(
            Math.random() * 15 + 15
        );
        document.getElementById("weatherDesc").textContent = [
            "晴天",
            "多云",
            "小雨",
            "阴天",
        ][Math.floor(Math.random() * 4)];
        document.getElementById("windSpeed").textContent =
            (Math.random() * 10 + 1).toFixed(1) + " km/h";
        document.getElementById("humidity").textContent =
            Math.floor(Math.random() * 40 + 40) + "%";
        document.getElementById("sunrise").textContent =
            "0" +
            Math.floor(Math.random() * 2 + 6) +
            ":" +
            (Math.floor(Math.random() * 3) + 10);
        document.getElementById("sunset").textContent =
            Math.floor(Math.random() * 2 + 18) +
            ":" +
            (Math.floor(Math.random() * 3) + 30);

        weatherResult.style.display = "flex";
    });

    // 6. 汇率转换功能
    const convertBtn = document.getElementById("convertCurrency");
    const conversionResult = document.getElementById("conversionResult");

    convertBtn.addEventListener("click", () => {
        const amount = parseFloat(document.getElementById("amount").value);
        const fromCurrency = document.getElementById("fromCurrency").value;
        const toCurrency = document.getElementById("toCurrency").value;

        // 模拟汇率转换
        const exchangeRates = {
            USD: { CNY: 6.8, EUR: 0.92, JPY: 148.5, GBP: 0.8 },
            CNY: { USD: 0.15, EUR: 0.14, JPY: 21.8, GBP: 0.12 },
            EUR: { USD: 1.09, CNY: 7.4, JPY: 161.2, GBP: 0.87 },
            JPY: { USD: 0.0067, CNY: 0.046, EUR: 0.0062, GBP: 0.0054 },
            GBP: { USD: 1.25, CNY: 8.5, EUR: 1.15, JPY: 185.2 },
        };

        const rate = exchangeRates[fromCurrency][toCurrency];
        const convertedAmount = (amount * rate).toFixed(2);

        document.getElementById("fromAmount").textContent = amount;
        document.getElementById("fromCurrencyText").textContent = fromCurrency;
        document.getElementById("convertedAmount").textContent =
            convertedAmount;
        document.getElementById("toCurrencyText").textContent = toCurrency;

        const now = new Date();
        document.getElementById("updateTime").textContent =
            now.toLocaleDateString() +
            " " +
            now.toLocaleTimeString().slice(0, 5);

        conversionResult.style.display = "block";
    });

    // 7. 媒体控制功能
    const playBtn = document.getElementById("playBtn");
    const musicBar = document.getElementById("musicBar");
    let isPlaying = false;

    playBtn.addEventListener("click", () => {
        isPlaying = !isPlaying;
        playBtn.innerHTML = isPlaying
            ? '<i class="fas fa-pause"></i>'
            : '<i class="fas fa-play"></i>';

        // 模拟进度条动画
        if (isPlaying) {
            let width = 0;
            const interval = setInterval(() => {
                if (width >= 100) {
                    clearInterval(interval);
                    isPlaying = false;
                    playBtn.innerHTML = '<i class="fas fa-play"></i>';
                    musicBar.style.width = "0%";
                } else {
                    width += 0.5;
                    musicBar.style.width = width + "%";
                }
            }, 50);
        }
    });

    // 视频控制
    const video = document.getElementById("tutorialVideo");
    const playVideoBtn = document.getElementById("playVideo");
    const pauseVideoBtn = document.getElementById("pauseVideo");
    const fullscreenBtn = document.getElementById("fullscreenBtn");

    playVideoBtn.addEventListener("click", () => {
        video.play();
    });

    pauseVideoBtn.addEventListener("click", () => {
        video.pause();
    });

    fullscreenBtn.addEventListener("click", () => {
        if (video.requestFullscreen) {
            video.requestFullscreen();
        } else if (video.webkitRequestFullscreen) {
            video.webkitRequestFullscreen();
        } else if (video.msRequestFullscreen) {
            video.msRequestFullscreen();
        }
    });

    const closeAdBtn = document.getElementById("closeAd");
    const adBanner = document.getElementById("adBanner");

    closeAdBtn.addEventListener("click", () => {
        adBanner.style.display = "none";
    });

    function updateWindowSize() {
        console.log(`窗口大小: ${window.innerWidth} x ${window.innerHeight}`);
    }

    window.addEventListener("resize", updateWindowSize);
    updateWindowSize();

    window.addEventListener("load", () => {
        const loadTime =
            window.performance.timing.domContentLoadedEventEnd -
            window.performance.timing.navigationStart;
        console.log(`页面加载时间: ${loadTime}ms`);
    });
});
